<template>
	<view>
		<view class="header">
			<image class="back" @click="backHandle" src="../../static/langwen/back.png" mode=""></image>
			<view class="center-btn">
				<view :class="isTop ? 'active' : ''" @click="isTop = true;">
					商品
					<view class="rect"></view>
				</view>
				<view :class="!isTop ? 'active' : ''" @click="isTop = false;">
					详情
					<view class="rect"></view>
				</view>
			</view>
			<image class="share" @click="openShare" src="../../static/langwen/share.png" mode=""></image>
		</view>
        <view style="height: 44px;"></view>
		<view class="images">
			<swiper @change="getCurrent" :circular="true">
				<swiper-item v-for="(item,index) in goodsPic" :key="index">
					<view class="swiper-item">
                        <img :src="item" alt="">
					</view>
				</swiper-item>
			</swiper>
			<view class="pag">
				{{ currentIndex + 1 }}/{{ goodsPic.length }}
			</view>
		</view>
		<view class="goods-header">
			<view class="title">
				{{ goodsName }}
			</view>
			<view class="sub">
				<view v-if="goodsFare" class="column">运费: {{ goodsFare }}元</view>
				<view class="column">销量: {{ goodsSale }}</view>
			</view>
			<view class="price">
				<view class="now">¥{{ goodsPrice }}</view>
				<view class="original" v-if="goodsOriginalPrice">¥{{ goodsOriginalPrice }}</view>
			</view>
		</view>
		<view class="list">
			<view class="row" v-if="goodsDiscount.length > 0">
				<view class="title">优惠信息:</view>
				<view class="flexbox">
					<view class="flexbox-item" v-for="(item,index) in goodsDiscount" :key="index">{{ item.name }}</view>
				</view>
			</view>
			<view class="row" @click="openPopup">
				<view class="title">规格:</view>
				<view class="flexbox">
					<view class="flexbox-item">{{ selected  || '请选择' }}</view>
				</view>
				<image class="icon" src="../../static/langwen/arrow_right_3.png" mode=""></image>
			</view>
		</view>
		<view class="recommend" v-if="goodsRecommend.length > 0">
			<view class="title">
				推荐商品
			</view>
			<view class="row">
				<item :item="item" v-for="(item,index) in goodsRecommend" :key="index"></item>
			</view>
		</view>
		<view class="detail" v-if="goodsRichtext">
			<view class="title">
				商品详情
			</view>
            <view class="richTxt" v-html="goodsRichtext"></view>
		</view>
        <view class="comment-container" v-if="goodsComment">
            <view class="title">
				商品评价
			</view>
            <view class="row" v-for="(item, index) in goodsComment" :key="index">
                <image class="avatar-user" :src="item.pic"></image>
                <view class="flexbox">
                    <view class="fraction">
                        <image class="star" v-for="(item,index) in item.stars" :key="index" src="../../static/langwen/star.png"></image>
                        <text v-show="item.stars === 5">非常好</text>
                        <text v-show="item.stars === 4">好</text>
                        <text v-show="item.stars === 3">一般</text>
                        <text v-show="item.stars === 2">差</text>
                        <text v-show="item.stars === 1">非常差</text>
                    </view>
                    <view class="content-user">{{ item.consultContent }}</view>
                    <view class="images" v-if="item.consultPic">
                        <image class="image" v-for="(item,index) in item.consultPic" :key="index" :src="item"></image>
                    </view>
				  <view class="system-reply" v-if="item.consultReplyIcon || item.consultReplyName || item.consultReply">
						<view class="system-reply-head">
							<image class="avatar-system" :src="item.consultReplyIcon"></image>
							<text>{{ item.consultReplyName }}</text>
						</view>
						<view class="system-reply-content">
							{{ item.consultReply }}
						</view>
					</view>
                </view>
            </view>
        </view>
		<view class="bottom" data-flex="cross:center">
			<view class="item" @click="collentHandle">
				<image class="img" :src="isCollent ? '../../static/langwen/collect_4.png' : '../../static/langwen/collect_3.png'" mode=""></image>
				收藏
			</view>
			<view class="item" @click="cartHandle">
				<image class="img" src="../../static/langwen/cart.png" mode=""></image>
				购物车
				<view class="badge" v-show="cartCount > 0">
				    {{ cartCount > 99 ? '99+' : cartCount }}
				</view>
			</view>
			<view class="btns" data-flex="main:justify" data-flex-box="1">
				<view class="btn blue" @click="handleBtn(1)" data-flex="main:center cross:center" style="margin-right: 10px"
					data-flex-box="1">
					加入购物车
				</view>
				<view class="btn yellow" @click="handleBtn(2)"  data-option="buy" data-flex="main:center cross:center" data-flex-box="1">
					立即购买
				</view>
			</view>
		</view>
		<popup v-if="popupShow" v-on:close-popup="closePopup" type="1" :shareTeacher="shareTeacher" :id="goodsId" :selected="selected"></popup>
		<!-- <share v-if="shareShow" v-on:close-share="closeShare" id=""></share> -->
	</view>
</template>

<script>
import demoData from '@/common/demoData';
import Api from '@/common/api';
import item from '@/components/langwen/item.vue';
import popup from '@/components/langwen/popup.vue';
function deepCopy(sender) {
    var result;
    if(typeof sender === 'object') {
        result = JSON.parse(JSON.stringify(sender));
    }else if(typeof sender === 'string') {
        result = sender + '';
    }else {
        result = sender;
    }
    return result;
}
function cleanEmpty(sender) {
    var temp = deepCopy(sender || []);
    var data = [];
    for(var i = 0; i < temp.length; i ++) {
        var item = temp[i];
        if(item !== null && item !== undefined && item !== '') {
            data.push(item);
        }
    }
    return data;
}
export default {
	name: 'detail',
    onLoad(option) {
        // option 上个页面传递过来的参数
        this.goodsId = option.id;
        this.smsGroupId = option.smsGroupId;
        this.pmsProductSkuId = option.pmsProductSkuId;
        this.shareTeacher = option.shareTeacher == 1;
		if(localStorage.getItem('langwen') === 'langwenApp') {
			this.isFromApp = true;
		} else {
			this.isFromApp = false;
		}
    },
    onShow() {
        this.$clound.cloudEvent('hideExistFrm');
    },
    onHide() {
        this.$clound.cloudEvent('showExistFrm');
    },
    onUnload() {
        this.$clound.cloudEvent('showExistFrm');
    },
	data() {
		return {
            smsGroupId: '',
            pmsProductSkuId: '',
            shareTeacher: false,
            // 商品 id
            goodsId: '',
            // 商品图片
            goodsPic: '',
            // 商品名称
            goodsName: '',
            // 商品运费
            goodsFare: 0,
            // 商品销量
            goodsSale: 0,
            // 商品价格
            goodsPrice: 0,
            // 商品原价
            goodsOriginalPrice: 0,
            // 商品优惠
            goodsDiscount: '',
            // 商品规格
            goodsOption: '',
            // 商品推荐
            goodsRecommend: [],
            // 商品富文本
            goodsRichtext: '',
            // 商品评价
            goodsComment: '',
            // 商品收藏状态
            isCollent: false,
            // 购物车数量
            cartCount: 0,
			skuId: '',
            // 打开规格弹窗
            popupShow: false,
            // 滚动条置顶
            isTop: true,
            // 轮播当前索引
            currentIndex: 0,
            // 选中规格, 默认为 ''
            selected: '',
			pageNum: 1,
			pageSize: 5,
			handleBtnNum: '',
			isFromApp: true
		}
	},
	components: {
		item,
		popup
    },
	// 上拉加载
	onReachBottom() {
		this.getCommonList('load');
	},
    watch: {
        isTop() {
            if(this.isTop) {
                // 点击顶部商品按钮
                window.scrollTo(0,0);
            } else {
                // 点击顶部详情按钮
                window.scrollTo(0, document.getElementsByClassName('detail')[0].offsetTop - document.getElementsByClassName('header')[0].offsetHeight);
            }
        }
    },
    created() {
        this.getGoodsDiscountInfo();
        this.getDetailData();
        this.getCommonList('headerRefreshing');
		this.getGoodsRecommend();
		this.getCartCount();
    },
    methods: {
		downloadTips() {
			if(!this.isFromApp) {
				this.$api.msg('请先下载APP');
				return false;
			} else {
				return true;
			}
		},
		handleBtn(num) {
			this.handleBtnNum = num;
			if(this.skuId) {
				this.joinCart();
			} else {
				this.openPopup();
			}
		},
		// 收藏
		collentHandle() {
			if(!this.downloadTips()) {
				return;
			}
			if(this.isCollent) {
			    this.uncollect();
			} else {
			    this.collect();
			}
		},
		closePopup(selected, goodsCount) {
            // 关闭规格弹窗
            this.popupShow = false;
            this.selected = selected;
			goodsCount = goodsCount ? goodsCount : 0;
			this.cartCount += goodsCount;
        },
        openPopup() {
			if(!this.downloadTips()) {
				return;
			}
            // 打开规格弹窗
			if(this.skuId) {
				this.$api.msg('当前商品只有一个规格');
				return;
			}
            this.popupShow = true;
        },
        openShare() {
			if(!this.downloadTips()) {
				return;
			}
            // 打开分享弹窗
            this.$clound.shareToApp(this.goodsId);
        },
		cartHandle() {
			if(!this.downloadTips()) {
				return;
			}
            // 跳转到购物车页面
			uni.switchTab({
				url: `/pages/langwen/cart`
			});
        },
		backHandle() {
            // 返回上一页面
			// uni.navigateBack();
            window.history.go(-1);
		},
		getCurrent(e) {
            // 获取当前轮播图的索引
			this.currentIndex = e.detail.current;
        },
        async getCartCount() {
            // 获取购物车数量
            var params = {};
            var data = await Api.apiCall('get', Api.goods.cartList, params);
			if(data.cartTotal) {
				this.cartCount = data.cartTotal.goodsCount || 0;
			}
        },
        async getDetailData() {
            // 获取商品详情
            var params = {
                'id': this.goodsId,
                'smsGroupId': this.smsGroupId,
                'pmsProductSkuId': this.pmsProductSkuId
            };
            var data = await Api.apiCall('get', Api.goods.goodsDetail, params);
            this.goodsPic = cleanEmpty(data.goods.goods.albumPics.split(','));
            this.goodsName = data.goods.goods.name;
            this.goodsFare = data.goods.goods.transfee;
            this.goodsSale = data.goods.goods.sale;
            this.goodsPrice = data.goods.goods.price;
            this.goodsOriginalPrice = data.goods.goods.originalPrice;
            // this.goodsRecommend = data.goods.typeGoodsList;
            this.goodsOption = data.goods.skuStockList;
            this.goodsRichtext = data.goods.goods.detailMobileHtml;
			this.isCollent = data.favorite;
			this.stock = data.goods.goods.stock;
			if(this.goodsOption.length === 1) {
				this.selected = `${this.goodsOption[0].sp1}${this.goodsOption[0].sp2}${this.goodsOption[0].sp3}${this.goodsOption[0].sp4}`,
				this.skuId = this.goodsOption[0].id;
			}
        },
		async getGoodsRecommend() {
			var params = {
			    'id': this.goodsId
			};
			var data = await Api.apiCall('get', Api.goods.relatedGoods, params);
			this.goodsRecommend = data.records;
		},
        async getGoodsDiscountInfo() {
            // 获取商品优惠信息
            var params = {
                'id': this.goodsId
            };
            var data = await Api.apiCall('get', Api.goods.findGoodsDiscountInfo, params);
            this.goodsDiscount = data.basicGiftsList;
        },
        async collect() {
			if(!this.downloadTips()) {
				return;
			}
            // 收藏
            var params = {
                'type': '1',
                'objId': this.goodsId
            };
            var data = await Api.apiCall('post', Api.goods.goodsCollect, params);
			this.isCollent = true;
			this.$api.msg('收藏成功');
        },
        async uncollect() {
			if(!this.downloadTips()) {
				return;
			}
            // 取消收藏
            var params = {
                'type': '1',
                'objId': this.goodsId
            };
            var data = await Api.apiCall('post', Api.goods.goodsCollect, params);
			this.isCollent = false;
			this.$api.msg('取消收藏成功');
        },
        async getCommonList(sign) {
            // 获取评论列表
			if(sign == 'headerRefreshing') {
				this.pageNum = 1;
			} else {
				this.pageNum ++;
			}
            var params = {
                'goodsId': this.goodsId,
                'pageNum': this.pageNum,
                'pageSize': this.pageSize
            };
            var data = await Api.apiCall('get', Api.goods.findGoodsComment, params);
            if(data.records.length > 0) {
				data.records.forEach((item) => {
					if(String(item.consultPic) == 'null' || String(item.consultPic) == '') {
						item.consultPic = '';
					} else {
						item.consultPic = cleanEmpty(String(item.consultPic).split(','))
					}
				});
				if(this.pageNum == 1) {
					this.goodsComment = [];
				}
                this.goodsComment = this.goodsComment.concat(data.records);
            }
        },
		canHandle() {
		    let  msg = null;
			if(this.stock < 1) {
		        msg = '库存不足';
		    }
            this.$api.msg(msg);
		    return !msg;
		},
		async payHandle(cartId) {
			if(!this.downloadTips()) {
				return;
			}
		    // 立即支付
		    var params = {
		        'type': '1',
		        'source': '2',
		        'orderType': '1',
		        'goodsId': this.goodsId,
		        'cartId': cartId,
		        'addressId': '',
		        'payType': '',
                'isBuyTeacherRecommendVideo': this.shareTeacher ? 1 : 2
		    };
		    var data = await Api.apiCall('get', Api.goods.priviewOrder, params);
		    // 路径
		    var url = '/pages/langwen/confirm';
		    // 参数
		    params.orderInfo = data;
		    uni.navigateTo({
		        url: `${url}?param=${encodeURIComponent(JSON.stringify(params))}`
		    });
		},
		async joinCart(e) {
			if(!this.downloadTips()) {
				return;
			}
		    // 加入购物车
		    if(!this.canHandle()) return;
		    var params = {
		        'goodsId': this.goodsId,
		        'skuId': this.skuId,
		        'total': 1,
                'buyRoad': this.handleBtnNum == 2 ? '2' : '1'
		    };
		    var data = await Api.apiCall('get', Api.goods.joinCart, params);
		    if(!data) {
		        // this.$api.msg('加入购物车失败');
		    }else if(this.handleBtnNum == 2) {
		        this.payHandle(data.id);
		    }else {
		        this.$api.msg('加入购物车成功');
				this.cartCount += 1;
		    }
		}
	}
}
</script>

<style lang="less">
page {
	background:rgba(245,245,245,1);
	padding-bottom: 50px;
}

.comment-container {
    padding: 0 30rpx;
	margin-bottom: 20rpx;
	background:rgba(255,255,255,1);
	.title {
		font-size:16px;
		font-weight:500;
		color:rgba(51,51,51,1);
        padding-top: 30rpx;
    }
    .row {
        display: flex;
        padding-top: 30rpx;
        .avatar-user {
            width: 66rpx;
            height: 66rpx;
            min-width: 66rpx;
            margin-right: 20rpx;
            border-radius: 50%;
        }
        .flexbox {
            flex-grow: 1;
            border-bottom: 1rpx solid rgba(231,230,230,1);
            .fraction {
                display: flex;
                align-items: center;
                margin-top: 18rpx;
                margin-bottom: 20rpx;
                .star {
                    width: 28rpx;
                    height: 28rpx;
                    margin-right: 10rpx;
                }
                text {
                    font-size: 28rpx;
                    font-weight:500;
                    color:rgba(25,25,25,1);
                }
            }
            .content-user {
                margin-bottom: 16rpx;
                font-size:30rpx;
                font-weight:400;
                color:rgba(74,75,77,1);
                line-height:46rpx;
            }
            .images {
                display: flex;
				flex-wrap: wrap;
                height: fit-content;
                margin-bottom: 20rpx;
                .image {
                    width: 188rpx;
                    height: 188rpx;
                    margin-right: 13rpx;
					margin-bottom: 13rpx;
                    &:last-child {
                        margin-right: 0;
                    }
                }
            }
            .system-reply {
                padding: 20rpx;
                background:rgba(238,238,238,1);
                border-radius:4px;
				margin-bottom: 16px;
                .system-reply-head {
                    display: flex;
                    align-items: center;
                    height: 40rpx;
                    margin-bottom: 10rpx;
                    .avatar-system {
                        width: 40rpx;
                        height: 40rpx;
                        margin-right: 10rpx;
                        border-radius: 50%;
                    }
                    text {
                        font-size:12px;
                        font-weight:400;
                        color:rgba(25,25,25,1);
                    }
                }
                .system-reply-content {
                    font-size:12px;
                    font-weight:400;
                    color:rgba(128,128,128,1);
                }
            }
        }
    }
}

.row:last-child {
    .flexbox {
        border-bottom: 0;
    }
}

.header {
    position: fixed;
    top: 0;
    right: 0;
    left: 0;
    z-index: 9;
	display: flex;
	justify-content: space-between;
	align-items: center;
	box-sizing: content-box;
	height: 44px;
	background:rgba(90,194,255,1);
	.back {
		width: 44px;
		height: 44px;
	}
	.share {
		width: 22px;
		height: 22px;
		margin-right: 13px;
	}
	.center-btn {
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 120px;
		height: 44px;
		font-size:18px;
		font-weight:500;
		color:rgba(255,255,255,0.79);
		.active {
			position: relative;
			font-size:18px;
			font-weight:500;
			color:rgba(255,255,255,1);
			.rect {
				position: absolute;
				left: 50%;
				bottom: -5px;
				transform: translateX(-50%);
				width:20px;
				height:3px;
				background:rgba(255,255,255,1);
				border-radius:2px;
			}
		}
	}
}
.images {
	position: relative;
	height: 375px;
	background:rgba(255,255,255,1);
	uni-swiper {
		height: 375px;
	}
	.swiper-item {
		height: 375px;
		display: flex;
		justify-content: center;
		align-items: center;
        img {
			width: 100%;
            height: 100%;
            object-fit: contain;
        }
	}
	.pag {
		display: flex;
		justify-content: center;
		align-items: center;
		position: absolute;
		right: 20px;
		bottom: 20px;
		width:50px;
		height:22px;
		background:rgba(0,0,0,0.3);
		border-radius:16px;
		font-size:14px;
		font-weight:400;
		color:rgba(255,255,255,1);
	}
}
.goods-header {
	padding: 15px;
	background:rgba(255,255,255,1);
	margin-bottom: 10px;
	.title {
		font-size:18px;
		font-weight:500;
		color:rgba(63,64,70,1);
		line-height:25px;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
	}
	.sub {
		display: flex;
		align-items: center;
		margin-top: 10px;
		font-size:12px;
		font-weight:400;
		color:rgba(127,129,141,1);
		.column {
			margin-right: 20px;
		}
	}
	.price {
		display: flex;
		align-items: center;
		margin-top: 13px;
		.now {
			font-size:20px;
			font-weight:500;
			color:rgba(255,92,1,1);
			margin-right: 10px;
		}
		.original {
			font-size:16px;
			font-weight:500;
			color:rgba(191,191,191,1);
			text-decoration: line-through;
		}
	}
}

.list {
	padding: 0 15px;
	background: #fff;
	margin-bottom: 10px;
	.row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 50px;
		border-bottom: 1px solid rgb(214,214,214);
		&:last-child {
			border-bottom: 0;
		}
		.title {
			font-size:14px;
			font-weight:400;
			color:rgba(63,64,70,1);
		}
		.flexbox {
			flex-grow: 1;
			display: flex;
			align-items: center;
			.flexbox-item {
				margin-left: 15px;
				font-size: 14px;
				font-weight: 400;
				color: rgba(63,64,70,1);
			}
		}
		.icon {
			width: 24px;
			height: 24px;
		}
	}
}

.recommend {
	padding: 15px 0;
	margin-bottom: 10px;
	background:rgba(255,255,255,1);
	.title {
		margin-left: 15px;
		font-size:16px;
		font-weight:500;
		color:rgba(51,51,51,1);
	}
	.row {
		display: flex;
		flex-wrap: wrap;
	}
}

.detail {
	padding: 15px;
	margin-bottom: 10px;
	background:rgba(255,255,255,1);
	.title {
		font-size:16px;
		font-weight:500;
		color:rgba(51,51,51,1);
        margin-bottom: 30rpx;
	}
    .richTxt {
        color: #3F4046;
        font-size: 28rpx;
        text-align: justify;
        img {
            max-width: 100%;
        }
    }
}

.bottom {
	position: fixed;
	bottom: 0;
	width: 100%;
	height: 50px;
	box-sizing: border-box;
	background: rgba(255, 255, 255, 1);
	padding: 0 15px 0 25px;
	border-top: 1px solid rgb(212,212,212);
	.item {
		overflow: visible;
		position: relative;
		margin-right: 25px;
		font-size: 10px;
		font-weight: 400;
		color: rgba(51, 51, 51, 1);
		line-height: 14px;
		padding-bottom: 3px;
		white-space: nowrap;
		text-align: center;
		.img {
			display: block;
			width: 24px;
			height: 24px;
			margin: 0 auto;
		}
		.badge {
			position: absolute;
			right: -10px;
			top: -3px;
			width:27px;
			height:14px;
			line-height: 13px;
			background:rgba(253,67,67,1);
			border-radius:7px;
			text-align: center;
			font-size:22rpx;
			font-weight:400;
			color:rgba(255,255,255,1);
		}
	}
	.btn {
		width: 112px;
		height: 32px;
		font-size: 15px;
		font-weight: 500;
		color: rgba(255, 255, 255, 1);
		line-height: 15px;
		border-radius: 18px;
	}
	.blue {
		background: rgba(90, 194, 255, 1);
	}
	
	.yellow {
		background: rgba(253, 155, 67, 1);
	}
}
</style>
